oo::class create Selection {
    superclass Plugin
    variable RenamedPadWidget

    constructor {renamedPadWidget} {
        set RenamedPadWidget $renamedPadWidget
        set padWidget [string trimleft $RenamedPadWidget _]

        bind $padWidget <Control-m> [list [self object] setAnchor]
        bind $padWidget <Escape> [list + [self object] unsetAnchor]
        bind $padWidget <Control-c> [subst {+ after idle {[self object] unsetAnchor}}]
        bind $padWidget <Control-x> [subst {+ after idle {[self object] unsetAnchor}}]
    }

    method ifExistsAnchor? {} {
        foreach m [$RenamedPadWidget mark names] {
            if {$m == "Anchor"} {return 1}
        }
        return 0
    }

    method setAnchor {} {
        $RenamedPadWidget tag remove sel 1.0 end
        $RenamedPadWidget mark set Anchor [$RenamedPadWidget index insert]
    }

    method unsetAnchor {args} {
        $RenamedPadWidget tag remove sel 1.0 end
        $RenamedPadWidget mark unset Anchor
    }

    method drawSelection {args} {
        if [my ifExistsAnchor?] {
            $RenamedPadWidget tag remove sel 1.0 end
            set currentId [$RenamedPadWidget index insert]
            if {[$RenamedPadWidget compare $currentId > Anchor]} {
                $RenamedPadWidget tag add sel Anchor $currentId
            } elseif {[$RenamedPadWidget compare $currentId < Anchor]} {
                $RenamedPadWidget tag add sel $currentId Anchor
            }
        }
    }

    method getPluginEvents {} {
        return {
            {afterInsert unsetAnchor}
            {afterDelete unsetAnchor}
            {afterReplace unsetAnchor}
            {afterMarkSetInsert drawSelection}
        }
    }
}